<template>
  <el-dialog ref="dialog" class="c-dialog-fixed" v-model="visible" :title="title" width="800px"
    :append-to-body="inDialog" @open="handleDialogOpen" @closed="handleDialogClosed">
    <list ref="listRef" :multiple-select="multipleSelect" :single-select="singleSelect" in-dialog>
    </list>
    <template #footer>
      <div class="c-flex">
        <div class="c-flex-item-auto c-text-left c-flex c-flex-wrap c-gap-5p">
          <el-tag v-for="(item, index) in listRef?.selectedRows" class="c-mg-r-5p" size="default" :key="item.id"
            closable effect="dark" disable-transitions @close="handleTagClose(index)">{{ item.name
            }}</el-tag>
        </div>
        <div><el-button type="primary" @click="handleSelected">选择</el-button></div>
      </div>
    </template>
  </el-dialog>
</template>
<script setup>
import list from "./list.vue";
import { ref, useTemplateRef } from "vue";
const props = defineProps({
  title: {
    type: String,
    default: "菜单列表"
  },
  inDialog: {
    type: Boolean,
    default: false
  },
  multipleSelect: {
    type: Boolean,
    default: false
  },
  singleSelect: {
    type: Boolean,
    default: false
  }
})
const visible = ref(false)
const emits = defineEmits(["select"])
const listRef = useTemplateRef("listRef")
let openParams = null;
//打开窗口
const open = (rows) => {
  visible.value = true
  openParams = rows;
}
//选择事件
const handleSelected = () => {
  visible.value = false
  emits("select", listRef.value.selectedRows);
}

//窗口打开事件
const handleDialogOpen = async () => {
  if (openParams) {
    listRef.value.selectedRows = [...openParams]
  }
  await listRef.value.getData();
}
//标签关闭事件
const handleTagClose = (index) => {
  listRef.value.selectedRows.splice(index, 1)
}
//窗口关闭后事件
const handleDialogClosed = () => {
  listRef.value.selectedRows.length = 0
}

defineExpose({
  open
})
</script>